<template>
  <div id="app">
    <fieldset>
      <legend>登入界面</legend>
      <div class="content" v-if="derail">
        <h1>列表展示</h1>
        <button @click="signOut">点击退出登录</button>
        <button @click="getList">点击获取列表数据</button>
        <h2>
          <img :src="userInfo.headimgurl" style="width: 50px" />
          昵称：
          <a href="">{{userInfo.nickname}}</a>
        </h2>
        <ul>
          <li v-for="(item, index) in list" :key="index">
            <b>{{ item.name }}</b>
            <button v-has:read="permissionBtns">查看</button>
            <button v-has:edit="permissionBtns">修改</button>
            <button v-has:delete="permissionBtns">删除</button>
            <button v-has:add="permissionBtns">增加</button>
          </li>
        </ul>
      </div>
      <div class="login" v-else>
        <h1>请登入</h1>
        <label for="username">用户名：</label>
        <input type="text" id="username" v-model="username" />
        <br />
        <label for="password">密码：</label>
        <input type="text" id="password" v-model="password" />
        <br />
        <button @click="record">登入</button>
      </div>
    </fieldset>
  </div>
</template>
<script>
import Vue from "vue";
Vue.directive("has", {
  inserted(el, binding) {
    let role = binding.arg;
    let userRole = binding.value;
    let hasRole = userRole.includes(role);
    if (!hasRole) {
      el.parentNode.removeChild(el);
    }
  },
});
export default {
  data() {
    return {
      derail: false,
      username: "",
      password: "",
      list: [],
      userInfo:{}
    };
  },
  methods: {
    loginApi(params = {}) {
      return fetch("http://chst.vip/users/login", {
        method: "post",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify(params),
      })
        .then((body) => body.json())
        .catch((err) => err.toString());
    },

    getListApi() {
      return fetch("http://chst.vip/students/getstulist?count=5", {
        mothod: "post",
        headers: {
          authorization: sessionStorage.getItem("user-token"),
        },
      })
        .then((body) => body.json())
        .catch((err) => err.toString);
    },

    async record() {
      let res = await this.loginApi({
        username: this.username,
        password: this.password,
      });
      if (res.state) {
        this.derail = true;
        this.userInfo = res.userInfo;
        sessionStorage.setItem("user-token", res.token);
        this.permissionBtns = res.permission.buttons;
        this.getList();
      } else {
        alert(res.msg);
      }
    },

    async getList() {
      let res = await this.getListApi();
      if (res.state) {
        console.log(res);
        this.list = res.data;
      }
    },

    signOut() {
      this.derail = false;
    },
  },
};
</script>

<style scoped>
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

li {
  border: 1px solid;
  margin: 10px;
  max-width: 500px;
}
</style>